#-*- coding:UTF-8 -*-
"""
Copyright 2009 http://code.google.com/p/picinmht/. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above
    copyright notice, this list of conditions and the following
    disclaimer in the documentation and/or other materials provided
    with the distribution.
  * Neither the name of http://code.google.com/p/picinmht/ nor the names of its
    contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import logging
import re
import base64
import pickle

from google.appengine.api import memcache
from google.appengine.runtime import apiproxy_errors
from google.appengine.ext import db

from model import *

def getUser(username, password):
    query = db.GqlQuery("SELECT * FROM User WHERE name=:1 AND password=:2", username, password)
    users = query.fetch(1)
    if users:
        return users[0]
    else:
        return None
    
def isLogin(self):
    sessionkey=self.request.cookies.get("sessionkey","NULL")
    addr=self.request.remote_addr
    session=None
    try:
        session=memcache.get("session_%s"%sessionkey)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if session is not None:
        return (True,session)
    query=db.GqlQuery ("SELECT * FROM Session WHERE sessionkey=:1 AND addr=:2",sessionkey,addr)
    sess=query.fetch(1)
    if sess:
        return (True, sess[0])
    else:
        return (False, None)

def getPicture(id):
    pic=None
    found=False
    try:
        pic=memcache.get("picuture_%d"%id)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if pic is None:
        imgs = db.GqlQuery ("SELECT * FROM Image WHERE picid = :1",id)
        for img in imgs:
            pic=img
            if found:
                logging.error("more than one copy of picid:%d?"%id)
            found=True
        if found:
            try:
                r=memcache.set("picuture_%d"%id,pic)
                if not r:
                    logging.error("Memcache set failed.")
            except apiproxy_errors.OverQuotaError, message:
                logging.error(message)
    return pic

def getSysInfo():
    sysinfo = None
    try:
        sysinfo=memcache.get("SysInfo_")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if sysinfo is not None:
        return sysinfo
    query = db.GqlQuery ("SELECT * FROM SysInfo")
    sys = query.fetch(1)
    if sys:
        sysinfo = sys[0]
        try:
            r=memcache.set("SysInfo_",sysinfo)
            if not r:
                logging.error("Memcache set sysinfo failed.")
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
    return sysinfo

def setSysInfo(sysinfo):
    sysinfo.put()
    try:
        r=memcache.set("SysInfo_",sysinfo)
        if not r:
            logging.error("Memcache set sysinfo failed.")
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)

def getPictutesFromMht(content):
    content=str(content)
    pattern=re.compile("Content-Type: image/jpeg\r\nContent-Transfer-Encoding: base64\r\nContent-Location: (.+)\r\n\r\n((.+\r\n)+)")
    ms=pattern.findall(content)
    if len(ms)==0:
        pattern=re.compile("Content-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\nContent-Location: (.+)\r\n\r\n((.+\r\n)+)")
        ms=pattern.findall(content)
    if len(ms) == 0:
        pattern=re.compile("Content-Type: image/png\r\nContent-Transfer-Encoding: base64\r\nContent-Location: (.+)\r\n\r\n((.+\r\n)+)")
        ms=pattern.findall(content)
    pics=[]
    for m in ms:
        img=base64.decodestring(m[1])
        pics.append(img)
    return pics

def getUserByName(name):
    user=None
    try:
        user=memcache.get("userbyname-%s"%name)
    except apiproxy_errors.OverQuotaError, message:
        logging.error(message)
    if user is not None:
        return user
    query = db.GqlQuery ("SELECT * FROM User WHERE name=:1",name)
    users = query.fetch(1)
    if users:
        user=users[0]
        try:
            r=memcache.set("userbyname-%s"%name,user)
            if not r:
                logging.error("Memcache set sysinfo failed.")
        except apiproxy_errors.OverQuotaError, message:
            logging.error(message)
        return user
    else:
        return None

def buildIndex():
    query=db.GqlQuery ("SELECT * FROM MhtIndex")
    dataindex=query.fetch(1)
    if len(dataindex)==1:
        idx=dataindex[0]
    else:
        idx=MhtIndex()
        idx.indexdata=pickle.dumps({})
        idx.put()
    

def getTobeDeleted():
    query=db.GqlQuery("SELECT * FROM TobeDelete")
    pics=query.fetch(1)
    if pics:
        return pics[0]
    else:
        pic=TobeDelete()
        pic.ids=[]
        pic.put()
        return pic